package com.gopay.common.cps.dao.ic.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.gopay.common.PageInfo;
import com.gopay.common.base.dao.impl.BaseDAOImpl;
import com.gopay.common.cps.dao.ic.IcSuccessOrderDtlDAO;
import com.gopay.common.domain.ic.IcSuccessOrderDtl;

/** 
 * @ClassName: IcSuccessOrderDtlDAOImpl 
 * @Description: 成功订单金额校验
 * @author liuyu 
 * @date 2016年12月22日 下午4:26:17  
 */
@Repository("icSuccessOrderDtlDAO")
public class IcSuccessOrderDtlDAOImpl extends BaseDAOImpl<IcSuccessOrderDtl, Serializable> implements IcSuccessOrderDtlDAO{
    /** logger */
    private static final Logger LOGGER = LoggerFactory.getLogger(IcSuccessOrderDtlDAOImpl.class);

    /**
     * 根据日期和分页信息查询差错订单
     * @author yhwpeng@126.com
     * @date 2018-05-23 15:41:28
     * @params
     * @param checkDateStart :
     * @param checkDateEnd :
     * @param pageInfo :
     * @return java.util.List<com.gopay.common.domain.ic.IcSuccessOrderDtl>
     */
    @Override
    public List<IcSuccessOrderDtl> findByDate(String checkDateStart,String checkDateEnd, String transType,PageInfo pageInfo) {
        Map<String, Object> param = new HashMap<>(2);
        param.put("checkDateStart", checkDateStart);

        StringBuilder hql = new StringBuilder("from IcSuccessOrderDtl i where to_date(i.checkDate,'yyyyMMdd') >= to_date(:checkDateStart,'yyyyMMdd')");
        if(StringUtils.isNotEmpty(checkDateEnd)){
            param.put("checkDateEnd",checkDateEnd);
            hql.append(" and to_date(checkDate,'yyyyMMdd') < to_date(:checkDateEnd,'yyyyMMdd')+1" );
        }
        if(StringUtils.isNotEmpty(transType)){
            param.put("transType",transType);
            hql.append(" and transType = :transType" );
        }
        hql.append(" order by checkDate");
        List<IcSuccessOrderDtl> result = findByHql(hql.toString(), param, pageInfo.getPageNum(),pageInfo.getPageSize());
        
        StringBuilder sbCount = new StringBuilder("select count(*) ");
        sbCount.append(hql);
        pageInfo.setTotalCount(findCountByHql(sbCount.toString(), param));
        return result;
    }

    /**
     * 根据日期查询订单长款和账务账款的数量
     * @author yhwpeng@126.com
     * @date 2018-05-23 14:03:25
     * @params
     * @param checkDateStart :
     * @param checkDateEnd :
     * @return java.util.List<java.lang.Object[]>
     */
    @Override
    public List<Object[]> calcByDate(String checkDateStart,String checkDateEnd,String transType) {
        final StringBuilder sqlBuild = new StringBuilder("select CHECK_DATE,diff_type, count(1) from IC_SUCCESS_ORDER_DTL i where to_date(i.check_Date,'yyyyMMdd') >= to_date(:checkDateStart,'yyyyMMdd')");
        final Map<String, Object> param = new HashMap<>();
        param.put("checkDateStart", checkDateStart);
        if(StringUtils.isNotEmpty(checkDateEnd)){
            param.put("checkDateEnd",checkDateEnd);
            sqlBuild.append(" and to_date(check_Date,'yyyyMMdd') < to_date(:checkDateEnd,'yyyyMMdd')+1" );
        }
        if(StringUtils.isNotEmpty(transType)){
            param.put("transType",transType);
            sqlBuild.append(" and trans_type = :transType" );
        }
        sqlBuild.append(" group by CHECK_DATE,diff_type order by i.CHECK_DATE");
        LOGGER.info("【内部对账管理 - 成功订单金额校验】查询差错订单类型及笔数，查询SQL为：{}" , sqlBuild.toString());
        return (List<Object[]>)getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery(sqlBuild.toString());
                if (param != null) {
                    Iterator<String> it = param.keySet().iterator();
                    while (it.hasNext()) {
                        String key = it.next();
                        Object value = param.get(key);
                        if (value instanceof Object[]) {
                            query.setParameterList(key, (Object[]) value);
                        } else {
                            query.setParameter(key, param.get(key));
                        }
                    }
                }
                return query.list();
            }
        });
    }
    
    /* 根据日期查询当日所有差错订单
     * @param checkDate
     * @param pageInfo
     * @return 
     * @see com.gopay.common.cps.dao.ic.IcSuccessOrderDtlDAO#findByDate(java.lang.String, com.gopay.common.PageInfo) 
     */ 
    @Override
    public Map<String, IcSuccessOrderDtl> findAllByDate(String checkDate) {
        Map<String, Object> param = new HashMap<>();
        param.put("checkDate", checkDate);
        String hql = "from IcSuccessOrderDtl i where i.checkDate = :checkDate";
        List<IcSuccessOrderDtl> list = findByHql(hql, param);
        Map<String, IcSuccessOrderDtl> result = new HashMap<>();
        for (IcSuccessOrderDtl icSuccessOrderDtl : list) {
            result.put(icSuccessOrderDtl.getGopayOrderId(), icSuccessOrderDtl);
        }
        return result;
    }

    /* 
     * @param checkDate 
     * @see com.gopay.common.cps.dao.ic.IcSuccessOrderDtlDAO#deleteByDate(java.lang.String) 
     */ 
    @Override
    public void deleteByDate(final String checkDate) {
        final Map<String, Object> param = new HashMap<>();
        param.put("checkDate", checkDate);
        final String hql = "delete from IcSuccessOrderDtl i where i.checkDate = :checkDate";
        getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createQuery(hql);
                int row = 0;
                if (param != null) {
                    query.setString("checkDate", checkDate);
                    row = query.executeUpdate();
                }
                return row;
            }
        });
    }
}
